﻿using Shop.Core.Redis;
using Shop.Core.Repository;
using Shop.Core.Share;
using Shop.IServices;
using Shop.Model.Dto.Common;
using Shop.Model.Entity.Use;

namespace Shop.Services;

public class SysAppService: AbstractService, ISysAppService
{
    private readonly RepositoryBase<UseUser> _userRepository;
    private readonly IRedisProvider _redisProvider;
    private readonly IAliyunAppService _aliyunAppService;

    public SysAppService(RepositoryBase<UseUser> userRepository,
        IRedisProvider redisProvider,
        IAliyunAppService aliyunAppService)
    {
        _userRepository = userRepository;
        _redisProvider = redisProvider;
        _aliyunAppService = aliyunAppService;
    }

    /// <summary>
    /// 通过ID发送验证码
    /// </summary>
    /// <param name="uId"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public async Task<AppResult> SendLoginCode(long uId)
    {
        var isExit = _userRepository.Where(x => x.Id.Equals(uId) && x.State != -1 && !string.IsNullOrEmpty(x.UnionId)).First();
        if (isExit != null)
        {
            var data = await _redisProvider.StringGetAsync("idc" + isExit.Tele);
            if (string.IsNullOrEmpty(data))
            {
                Random rad = new();
                int code = rad.Next(1000, 10000);
                string smsCodeTemp = "{\"code\":\"" + code + "\"}";
                _ = await _redisProvider.StringSetAsync("idc" + isExit.Tele, code.ToString(), new TimeSpan(0, 2, 0));
                return await _aliyunAppService.SendSms(new SendSmsDto
                {
                    Tel = isExit.Tele,
                    Temp = "SMS_265650303",
                    TempParam = smsCodeTemp
                });
            }
            else
                return new AppResult(400, "失败","请不要频繁发送短信");
        }
        else
            return new AppResult(400, "失败", "用户不存在或者未激活");
    }
    
    
}